package org.bpms.service.admin;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.bpms.model.admin.Srole;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

/**
 * 后台角色业务处理
 * @author hupei
 *
 */
public class RoleService {
	
	/**
	 * 保存角色
	 * @param role
	 * @return
	 */
	@Before(Tx.class)
	public Srole saveOrUpdate(Srole role){
		if (null != role.getStr("id")){
			role.update();
		}else{
			role.set("id", UUID.randomUUID().toString().replaceAll("-", ""));
			role.save();
		}
		return role;
	}
	
	/**
	 * 查询属于同一角色的用户个数，在删除角色时可能会用到
	 * @param roleId
	 * @return
	 */
	public int findUser(String roleId){
		int have = 0;
		List<Record> record = Db.find("select count(*) as num from suserrole "
				+ "where rid=?" , roleId);
		if (null != record && record.size() > 0){
			have = record.get(0).getInt("num");
		}
		return have;
	}
	
	/**
	 * 查询用户所属的角色
	 * @param uid
	 * @return
	 */
	public List<Srole> getRoleFromUser(String uid){
		List<Srole> ls = Srole.me.find("select a.* from srole a , suserrole b "
				+ "where a.id = b.rid and b.uid=?" , uid);
		return ls;
	}
	
	/**
	 * 根据id查询角色
	 * @param roleId
	 * @return
	 */
	public Srole findById(String roleId){
		return Srole.me.findById(roleId);
	}
	/**
	 * 根据菜单得到拥有菜单的角色
	 * @param menuid
	 * @param pageNumber
	 * @param pageSize
	 * @param orderField
	 * @param orderDirection
	 * @param pagemap
	 */
	public void findRoleFromMenu(String menuid,Integer pageNumber,Integer pageSize,
			           String orderField,String orderDirection,Map<String,Object> pagemap){
		Page<Srole> rolePage = Srole.me.paginate(pageNumber, pageSize, 
				"select id , text",  "from srole where id in(select rid from srolemenu"
						+ " where mid=?) order by "+orderField+" "+orderDirection+"", menuid);
		pagemap.put("pageSize", rolePage.getPageSize());//页面大小
		pagemap.put("totalRow", rolePage.getTotalRow());//总行数
		pagemap.put("pageCurrent", rolePage.getPageNumber());//当前页号
		pagemap.put("orderField", orderField);//排序列名
		pagemap.put("orderDirection", orderDirection);//排序方式
		pagemap.put("pageData", rolePage.getList());//页面数据
	}
	
	/**
	 * 保存角色菜单关系
	 * @param maptree
	 * @param roleId
	 */
	@Before(Tx.class)
	public void updateMenuRelation(Map maptree , String roleId){
		if (null != maptree.get("pId") && !maptree.get("id").equals("-1")){
			if ((boolean)maptree.get("checked")){
				List<Record> records = Db.find("select * from srolemenu where rid=? and mid=?",
						                        roleId , maptree.get("id"));
				if (null == records || records.size() == 0){
					Record rolemenu = new Record().set("mid", maptree.get("id"))
							.set("rid", roleId);
					Db.save("srolemenu", rolemenu);
				}
			}else{
				List<Record> records = Db.find("select * from srolemenu where rid=? and mid=?",
                        roleId , maptree.get("id"));
				if (null != records && records.size() > 0){
					Db.deleteById("srolemenu", records.get(0).getInt("id"));
				}
			}
		}
		if (null != maptree.get("children")){
			List list = (ArrayList) maptree.get("children");
			if (null != list && list.size() > 0){
				for (int i = 0 ; i < list.size() ; i++){
					Map temp = (Map)list.get(i);
					if (null != temp){
						updateMenuRelation(temp , roleId);
					}
				}				
			}
		}
	}
	
	/**
	 * 保存角色菜单关系
	 * @param maptree
	 * @param roleId
	 */
	@Before(Tx.class)
	public void updateUserRelation(Map maptree , String roleId){
		if (null != maptree.get("pId") && !maptree.get("id").equals("-1")){
			if ((boolean)maptree.get("checked")){
				List<Record> records = Db.find("select * from suserrole where rid=? and uid=?",
						                        roleId , maptree.get("id"));
				if (null == records || records.size() == 0){
					Record roleuser = new Record().set("uid", maptree.get("id"))
							.set("rid", roleId);
					Db.save("suserrole", roleuser);
				}
			}else{
				List<Record> records = Db.find("select * from suserrole where rid=? and uid=?",
                        roleId , maptree.get("id"));
				if (null != records && records.size() > 0){
					Db.deleteById("suserrole", records.get(0).getInt("id"));
				}
			}
		}
		if (null != maptree.get("children")){
			List list = (ArrayList) maptree.get("children");
			if (null != list && list.size() > 0){
				for (int i = 0 ; i < list.size() ; i++){
					Map temp = (Map)list.get(i);
					if (null != temp){
						updateUserRelation(temp , roleId);
					}
				}				
			}
		}
	}
	
	/**
	 * 检索所有的角色
	 * @param roleid
	 * @param text
	 * @param pageNumber
	 * @param pageSize
	 * @param orderField
	 * @param orderDirection
	 * @param pagemap
	 */
	public void findRoleFromMenu(String roleid,String text,Integer pageNumber,Integer pageSize,
	           String orderField,String orderDirection,Map<String,Object> pagemap){
		StringBuffer sql = new StringBuffer("from srole where 1=1 ");
		if (null != roleid){
			sql.append(" and id='"+roleid+"'");
		}
		if (null != text){
			sql.append(" and text like '%"+text+"%'");
		}
		sql.append(" order by "+orderField+" "+orderDirection);
        Page<Srole> rolePage = Srole.me.paginate(pageNumber, pageSize, "select id , text", sql.toString());
		pagemap.put("pageSize", rolePage.getPageSize());//页面大小
		pagemap.put("totalRow", rolePage.getTotalRow());//总行数
		pagemap.put("pageCurrent", rolePage.getPageNumber());//当前页号
		pagemap.put("orderField", orderField);//排序列名
		pagemap.put("orderDirection", orderDirection);//排序方式
		pagemap.put("pageData", rolePage.getList());//页面数据
}	
	
	/**
	 * 删除角色
	 * @param roleId
	 */
	@Before(Tx.class)
	public void delRole(String roleId){
		Db.update("delete from srolemenu where rid=?" , roleId);//删除菜单关联
		Db.update("delete from suserrole where rid=?" , roleId);//删除用户关联
		Srole.me.deleteById(roleId);
	}
}
